const createXMLHttpRequestHook = ({ onRequest, onResponse }) => {
  class MockXMLHttpRequest extends XMLHttpRequest {
    // _send = false;
    ctx: ContextProps = {
      method: "",
      url: "",
      resource: "xhr",
      resBody: "",
      data: null,
      headers: {},
      setHeader: function (key: string, value: string): void {
        // throw new Error("Function not implemented.");
      },
    };
    private _open: () => void;
    private _isSend: boolean;
    open(
      method: string,
      url: string,
      async?: boolean,
      username?: string,
      password?: string
    ): void {
      this.ctx.url = url;
      this.ctx.method = method;
      this.ctx.setHeader = (key: string, value: string) => {
        if (!this.ctx.headers) {
          this.ctx.headers = {};
        }
        if (value) {
          this.ctx.headers[key] = value;
        } else {
          delete this.ctx.headers[key];
        }
      };
      this._open = () => {
        super.open(method, this.ctx.url);
      };
    }
    setHeader(key: string, value: string) {
      super.setRequestHeader(key, value);
    }
    setRequestHeader(name: string, value: string): void {
      if (value) {
        this.ctx.headers[name] = value;
      } else {
        delete this.ctx.headers[name];
      }
    }
    responseText: string;
    response: string;
    status: number;

    _sendMockResponse(resBody) {
      this.responseText = resBody;
      this.response = resBody;
      this.readyState = XMLHttpRequest.DONE;
      this.status = 200;
      this.dispatchEvent(new Event("loadend"));

      this.dispatchEvent(new Event("readystatechange"));
    }
    listeners = []
    addEventListener<K extends keyof XMLHttpRequestEventMap>(
      type: K,
      listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any,
      options?: boolean | AddEventListenerOptions
    ): void;
    addEventListener(
      type: string,
      listener: EventListenerOrEventListenerObject,
      options?: boolean | AddEventListenerOptions
    ): void;
    addEventListener(
      type: unknown,
      listener: any,
      options?: unknown
    ): void {
      const that = this
      console.log("监听收拾收拾", type, listener);
      // this.listeners.push({
      //   type,
      //   listener,
      //   options
      // })
      super.addEventListener(type as any,function(e){
         if(type==='readystatechange'&&this.readyState===4){
            console.log('完成')
           that.listeners.push(listener)
         }else{
          listener.call(this,e)
         }
      },options)
    }

    _sendRequest() {
      const that = this;
      that._open();
      that._isSend = true;
      console.log("发送");
      let onreadystatechange
      setTimeout(() => {
        console.log("到我这里了onreadystatechange");
         onreadystatechange = that.onreadystatechange;
        that.onreadystatechange = () => {
        };
      });

      super.addEventListener("readystatechange", function () {
        that.readyState = that._readyState();
       
        if (that.readyState === 4) {
          that.status = 200;
          if (onResponse) {
            that.ctx.resBody = that._response();
            onResponse(that.ctx, {
              send(resBody: ResBodyType) {
                that.response = resBody;
                that.responseText = resBody;
              },
              next(ctx: ContextProps) {
                const loadend = that.onloadend;
                that.onloadend = function () {
                  console.log("sss");
                };
                setTimeout(() => {
                  that.response =ctx.resBody;

                  that.responseText = ctx.resBody;
                  if (loadend) {
                    loadend.call(that);
                  }
                  
                    if(onreadystatechange){

                      onreadystatechange.call(that)
                  }
                  that.listeners.filter(v=>v.type==='readystatechange').forEach(item=>{
                    item.listener.call(that)
                  })
                  // that.dispatchEvent(new Event("readystatechange"));
                  // that._sendMockResponse('sss')
                  console.log("延时返回");
                }, 2000);
              },
            });
          } else {
            console.log("没有处理", that._response());
            that.response = that._response();
            that.responseText = that._response();
          }
        }else{
          that.status = 0;
          if(onreadystatechange){
            console.log('that.readyState==>',that.readyState)
            onreadystatechange.call(that)
          }
          // that.listeners.filter(v=>v.type==='readystatechange').forEach(item=>{
          //   item.listener.call(that)
          // })
        }
      });
      Object.keys(this.ctx.headers).forEach((key) => {
        that.setHeader(key, this.ctx.headers[key]);
      });
      //   that._send();
      super.send(this.ctx.data);
    }
    readyState: number;
    _readyState() {
      return super.readyState;
    }
    _response() {
      return super.response;
    }
    send(body?: Document | XMLHttpRequestBodyInit): void {
      const that = this;
      that.ctx.data = body;
      console.log("发送改变", body);
      if (onRequest) {
        onRequest(this.ctx, {
          send(resBody) {
            setTimeout(() => {
              that._sendMockResponse(resBody);
            }, 10);
          },
          next(config) {
            that._sendRequest.call(that);
          },
        });
      } else {
        that._sendRequest.call(that);
      }
    }
  }
  window.XMLHttpRequest = MockXMLHttpRequest;
};
export default createXMLHttpRequestHook;
